package Socket;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * 客户端
 * @author 徐梦轲
 * @create 2022-06-25 10:25
 */
public class Client {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public Client(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("客户端启动");
            //构造请求

            System.out.println("请输入:");
            String request = sc.nextLine();
            if (request.equals("exit")) return;

            //发送请求
            DatagramPacket sendPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(sendPacket);
            //接收响应
            DatagramPacket resPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(resPacket);
            String response = new String(resPacket.getData(),0,resPacket.getLength());
            //显示
            String log = String.format("request : %s,response : %s",request,response);
            System.out.println(log);
        }

    }

    public static void main(String[] args) throws IOException {
        Client client  = new Client("127.0.0.1",9090);
        client.start();
    }
}
